// pages/index/bill/billList.js
const app = getApp();
var util = require('../../util/util.js');
var date = require('../../util/date.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    navbar: ['按时间', '按距离'],
    currentTab: 1,
    loading: true, // 显示等待框
    title: '加载中...',// 状态
    list: [], // 数据列表
    hasLocation: false,
    location:{},
    offset:1,
    limit: 10,
    hasMoreData:true,//是否有更多数据
    total:0,//数据总数
    billAddress:"",//经度，纬度
    isRate: true,//是否显示年利率
    isList: true,
    isUser: false,
  },
  //排序点击
  navbarTap: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.idx + 1;
    if (index===2){//如果是按距离排序
      this.checkSettingStatu(index);
    }else{
      this.setData({
        currentTab: index,
        offset: 1
      })
      //console.info("排序中~");
      this.getList(1, this.data.limit, this.data.billAddress, index);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) { // options 为 board页传来的参数
    var islocation = app.globalData.hasLocation;
    var oLocation = app.globalData.location;
    var billAddress="";
    this.setData({
      hasLocation: islocation,
      location: oLocation
    })
    if (islocation) {
      var oLongitude = oLocation.longitude;
      var oLatitude = oLocation.latitude;
      billAddress = oLongitude + "," + oLatitude;//经度,纬度    
    }
    this.setData({
      billAddress: billAddress
    })
    //console.info("onload中~");
    //初始化加载数据(按时间)
    this.getList(this.data.offset, this.data.limit, this.data.billAddress, this.data.currentTab);
    //数据加载完提示授权
    if (!islocation){
      setTimeout(() => {
        //第一次授权地理位置
        let that = this;
        wx.authorize({
          scope: 'scope.userLocation',
          success: (resp) => {
            //获取位置
            wx.getLocation({
              success: function (res3) {
                //设置全局地理位置
                app.globalData.hasLocation = true;
                app.globalData.location = {
                  "longitude": res3.longitude,
                  "latitude": res3.latitude
                }
                //设置当前排序方式
                let billAddress = res3.longitude + "," + res3.latitude //经度,纬度 
                let location = { "longitude": res3.longitude, "latitude": res3.latitude }
                //重新加载
                //console.info("获取地理位置后~");
                //that.getList(1, 10, billAddress, 1);
                that.setData({
                  currentTab: 1,
                  hasLocation: true,
                  billAddress: billAddress,//经度,纬度 
                  location: location
                })
              }
            })
          },
        })
      }, 1000);
    }

    //用户信息
    let openId = (wx.getStorageSync('openId'));
    // console.info("判断是否需要获取用户信息，是否显示button=" + !openId);
    if (!openId) {
      //不存在user
      this.setData({
        isUser: true
      })
    } else {
      //存在user 可以不用显示按钮
      this.setData({
        isUser: false
      })
    }
  },
  //获取用户信息
  getUserInfo: function (e) {
    let that = this
    // console.log(e)
    if (e.detail && e.detail.userInfo) {//存在userInfo
      //调方法,设置缓存
      
      that.myLogin(e.detail.userInfo)
    } else {
      //不存在
      app.myWarn();
      that.setData({
        isUser: true
      })
    }
  },
  //获取列表方法
  getList:function(offset,limit,billAddress,sortType){
    const that = this; 
    //console.info(billAddress);
    // 拼接请求url
    const url = app.globalData.api + "/wechat/bill/list";
    // 请求数据
    wx.request({
      url: url,
      method: "POST",
      data: { "offset": offset, "limit": limit, "billAddress": billAddress, "type": sortType },
      success: function (res) {
        if (res.data && res.data.rows){

          //console.info(res.data.rows);
          //处理数据
          res.data.rows.forEach((item, index) => {
            //处理创建时间间隔
            var leadTime = (new Date() - item.createTime) / (1000 * 60);
            item.leadTime = parseInt(leadTime);
            if (leadTime<60){//小于60分钟,直接显示分钟
              item.leadTime = parseInt(leadTime);
            } else if (leadTime<(24*60)){//小于24小时,显示小时
              item.leadHour = parseInt(leadTime/60);
            }else{//其余都显示天数
              item.leadDay = parseInt(leadTime/60/24);
            }
            //处理距离
            if (item.billDistance<10000){
              if (item.billAddressname) {
                item.distance = Math.round(item.billDistance) + "km" + item.billAddressname;
              } else {
                item.distance = Math.round(item.billDistance) + "km";
              }
            } else if (item.billDistance<1){
              if (item.billAddressname){
                item.distance = item.billDistance * 1000 + "m" + item.billAddressname;
              }else{
                item.distance = item.billDistance * 1000 + "m";
              }
            }else{
              if (item.billAddressname) {
                item.distance = "太遥远了~" + item.billAddressname;
              } else {
                item.distance = "太遥远了~" ;
              }
            }
            //处理十万扣
            if(item.debit10=="--"){
              item.myDebit10 = null;
            } else {
              item.myDebit10 = item.debit10;
            }
            //处理竞价方式
            if (item.quotationMethod == 2){
              item.jingjia = "竞价"
            }
          })
        }
        var listTem = that.data.list;
        if (res.data && res.data.rows && res.data.total){
          // 赋值
          if (that.data.offset == 1) {
            listTem = []
          }
          var list = res.data.rows;
          //是否有多页数据
          if (res.data.total < that.data.limit) {
            //只有一页
            //console.info("只有一页");
            that.setData({
              isList: true,
              list: listTem.concat(list),
              total: res.data.total,
              hasMoreData: false,
              loading:false
            })
          }
          //当前页小于总页数 可继续加载
          if (that.data.offset < Math.ceil(res.data.total / that.data.limit)){
            //console.info("共有 " + Math.ceil(res.data.total / that.data.limit) + " 页数据,现在加载第 " + that.data.offset+" 页");
            that.setData({
              isList: true,
              list: listTem.concat(list),
              total: res.data.total,
              hasMoreData: true,
              offset: that.data.offset + 1,
              loading: false
            })
          }else{
            //最后一页
            //console.info("最后一页了");
            that.setData({
              hasMoreData: false
            })
          }
        }else{
          //空的
          that.setData({
            isList:false,
            list: [],
            total: 0,
            loading: false // 关闭等待框
          })
        }
      },
      fail:function(err){
        that.setData({
          isList: false,
          list: [],
          total: 0,
          loading: false // 关闭等待框
        })
      }
    })
  },
  // 点击距离排序检测地理位置授权状态
  checkSettingStatu: function (index) {
    var that = this;
    wx.getSetting({
      success: function success(response) {
        var authSetting = response.authSetting;
        if (!authSetting["scope.userLocation"]) {
          // 不是第一次授权  且没有授权的
          if (authSetting['scope.userLocation'] === false) {
            wx.showModal({
              title: '用户未授权地理位置信息',
              content: '该操作需要获取您的位置信息，请按确定进入授权管理中对“地理位置”进行授权，最后重新进入即可查看。',
              success: function (res) {
                if (res.confirm) {
                  wx.openSetting({
                    success: function success(res2) {
                      wx.getLocation({
                        success: function (res3) {
                          //设置全局地理位置
                          app.globalData.hasLocation = true;
                          app.globalData.location = {
                            "longitude": res3.longitude,
                            "latitude": res3.latitude
                          }
                          //设置当前排序方式
                          index = 1;
                          that.setData({
                            currentTab: 1,
                            hasLocation: true,
                            billAddress: res3.longitude + "," + res3.latitude,//经度,纬度 
                            location: {
                              "longitude": res3.longitude,
                              "latitude": res3.latitude
                            }
                          })
                        }
                      })
                    }
                  });
                }
              }
            })
          } else {
            //第一次授权
            wx.authorize({
              scope: 'scope.userLocation',
              success: (resp) => {
                //获取位置
                wx.getLocation({
                  success: function (res3) {
                    //设置全局地理位置
                    app.globalData.hasLocation = true;
                    app.globalData.location = {
                      "longitude": res3.longitude,
                      "latitude": res3.latitude
                    }
                    //设置当前排序方式
                    index = 1;
                    that.setData({
                      currentTab: 1,
                      hasLocation: true,
                      billAddress: res3.longitude + "," + res3.latitude,//经度,纬度 
                      location: {
                        "longitude": res3.longitude,
                        "latitude": res3.latitude
                      }
                    })
                  }
                })
              },
            }) 

          } 
        }else { 
          //已经授权了的
          wx.getLocation({
            success: function (res3) {
              //设置全局地理位置
              app.globalData.hasLocation = true;
              app.globalData.location = {
                "longitude": res3.longitude,
                "latitude": res3.latitude
              }
              let billAddress = res3.longitude + "," + res3.latitude;
              //设置当前排序方式
              that.setData({
                currentTab: index,
                offset: 1,
                hasLocation: true,
                billAddress: billAddress,//经度,纬度 
                location: {
                  "longitude": res3.longitude,
                  "latitude": res3.latitude
                }
              })
              //调用方法
              that.getList(1, that.data.limit, billAddress, index);
            }
          })
        }
      }
      
    });
  },
  //点击分享
  onShareAppMessage: function (options) {
    var shareObj = {
      title: '票据列表',
      path: '/pages/bill/billList/billList',
      success: function (res) {
        console.info("转发成功")
      },
      fail: function (res) {
        console.info("取消转发");
      }
    };
    if (options.from == 'button') {
      var eData = options.target.dataset;
      //console.log(eData.id);
      //修改 shareObj 中的内容
      shareObj.title = '票据详情';
      shareObj.path = '/pages/bill/billDetail/billDetail?id=' + eData.id;
    }
    return shareObj;
  },
  //登录
  myLogin(userInfo) {
    let that = this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        if (res.code) {
          // console.info(res.code);
          var url = app.globalData.api + "/wechat/user/login";
          var data = {
            code: res.code,
            userName: userInfo.nickName,
            headPortrait: userInfo.avatarUrl
          }
          wx.request({
            url: url,
            data: data,
            method: 'post',
            success: function (res2) {
              // console.info(res2.data);
              if (res2.data.code == 0) {
                //设置全局用户信息
                app.globalData.userInfo = userInfo;
                app.globalData.isUser = true
                //设置当前页面的信息
                that.setData({
                  isUser: false
                })
                //设置openId缓存
                wx.setStorageSync('openId', res2.data.openid);
                if (res2.data.token) {
                  wx.setStorageSync('token', res2.data.token);
                }
              } else {
                wx.showToast({
                  title: res2.errMsg,
                  icon: "none"
                })
              }

            },
          })
        } else {
          wx.showToast({
            title: "网络错误，请稍后重试~",
            icon: "none"
          })
        }
      }
    })
  },
  //提示弹层
  myWarn() {
    var that = this;
    wx.showModal({
      title: '用户未授权',
      content: '如需获取用户联系方式，请按确定并在授权管理中选中“用户信息”，进行授权，最后再重新进入小程序即可正常使用。',
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          that.regetInfo();
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //调出重新授权界面
  regetInfo() {
    var that = this;
    wx.openSetting({
      success: function success(res) {
        if (res.authSetting["scope.userInfo"] == true) {
          wx.getUserInfo({
            success: function (data2) {
              //设置全局用户信息
              app.globalData.userInfo = data2.userInfo;
              app.globalData.isUser = true
            }
          })
        }
      }
    });
  },
  //点击电话，跳出弹层
  calling: function (e) {
    var openId = (wx.getStorageSync('openId'));
    if (!openId){
      app.myWarn();
      return
    }
    var mobile = e.currentTarget.dataset.mobile;
    var username = e.currentTarget.dataset.username;
    var image = e.currentTarget.dataset.img;
    wx.showModal({
      title: '提示',
      confirmText:"是",
      confirmColor:"#004884",
      cancelText:"否",
      content: '是否拨打' + username+'电话：'+mobile,
      //content: html,
      success:(res)=>{
        if (res.confirm){
          //点击确认
          wx.makePhoneCall({
            phoneNumber: mobile, //此号码并非真实电话号码，仅用于测试  
            success: function (suc) {
              console.log(suc)
            },
            fail: function (err) {
              wx.showToast({
                title: err.errMsg,
                icon: "none"
              })
            }
          })
        }
      }
    })
  },
  //点击我要发布，跳转发布页面
  toBillRelease(){
    var openId = (wx.getStorageSync('openId'));
    if (openId){
      //存在openId 允许跳转
      wx.navigateTo({
        url: '../billRelease/billRelease'
      })
    }else{
      app.myWarn();
      return
    }
      
  },
  //点击列表，跳转详情
  toBillDetail: function(e){
    //console.info("跳转列表，票据信息=" + e.currentTarget.dataset.id);
    var oData = e.currentTarget.dataset;
    //console.info(oData);
    wx.navigateTo({
      url: '../billDetail/billDetail?id=' + oData.id + '&distance=' + oData.distance + '&time=' + oData.time, //传参跳转即可
    })
  },
  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
    this.setData({
      offset:1
    })
    //console.info("onPullDownRefresh中~");

    this.getList(1, this.data.limit, this.data.billAddress, this.data.currentTab);
    wx.showLoading({
      title: '正在刷新数据',
    })
    setTimeout(function () {
      wx.hideLoading();
      wx.stopPullDownRefresh();
    }, 2000)   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    const that = this;
    if (that.data.hasMoreData){
      //存在多页数据
      that.getList(that.data.offset, that.data.limit, that.data.billAddress, that.data.currentTab);
      wx.showLoading({
        title: '正在加载',
      })
      setTimeout(function () {
        wx.hideLoading()
      }, 1000)
    }else{
      wx.showToast({
        title: '没有更多数据了~',
        icon: 'none',
      })
    }
  },
})